<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/15
 * Time: 17:14
 */

namespace app\api\validate;


use app\lib\exception\ParameterException;
use app\lib\exception\ProductException;

class ProductParameter extends BaseValidate
{
    protected $rule=[
        'id'=>'isPositiveInt',
        'name'=>'require',
        'price'=>'require|checkPrice',
        'stock'=>'require|isPositiveInt',
        'category_id'=>'require|isPositiveInt',
        'pay'=>'require|isPositiveInt',
        'grounding'=>'require|isPositiveInt',
        'img'=>'require|checkPictures',
        'picture'=>'require|checkPictures',
        'property'=>'require|checkProperty'
    ];
    protected $singleRule=[
        'img_id'=>'require|isPositiveInt',
    ];
    protected  $message=[
        'id'=>'商品id格式不正确',
        'name'=>'商品名称不能为空',
        'price'=>'价格不能为空',
        'stock'=>'库存量必须为正整数',
        'category_id'=>'分类id必须是正整数',
        'pay'=>'线上交易参数不能为空',
        'grounding'=>'上线状态不能为空',
        'img'=>'商品图片不能为空',
        'picture'=>'商品主图不能为空',
        'property'=>'商品规格不能为空'
    ];

    /**
     * 验证商品信息
     * @param $value
     * @return bool
     * @throws ProductException
     */
    public function checkPrice($value){
        if (preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value)){
            return true;
        }else{
            throw new ProductException([
                'msg'=>'商品价格参数错误'
            ]);
        }
    }

    /**
     * 检查商品图片
     * @param $valus
     * @return bool
     * @throws ParameterException
     */
    public function checkPictures($values){
        if (empty($values)){
            throw new ParameterException([
                'msg'=>'商品图片不能为空'
            ]);
        }
        if (!is_array($values)){
            throw new ParameterException([
                'msg'=>'商品图片参数不正确'
            ]);
        }
        foreach ($values as $value){
            $this->checkPicture($value);
        }
        return true;
    }
    /**
     * @param $value
     * @return bool
     * @throws ParameterException
     */
    public function checkPicture($value){
        $validate  = new BaseValidate($this->singleRule);
        $result = $validate->check($value);
        if (!$result){
            throw new ParameterException([
                'msg'=>'商品图片参数不正确'
            ]);
        }
        return true;
    }

    /**
     * 商品规格检查
     * @return bool
     * @throws ParameterException
     */
    public function checkProperty($values){
        if (empty($values)){
            throw new ParameterException([
                'msg'=>'商品规格参数不能为空'
            ]);
        }
        if (!is_array($values)){
            throw new ParameterException([
                'msg'=>'商品规格参数格式不正确'
            ]);
        }
        return true;
    }


}